/* 商品搜索JS
 * @copyright  Copyright (c) 中国追溯
*/
var page = pagesize;
var curpage = 1;
var hasmore = true;
var footer = false;
var keyword = decodeURIComponent(getQueryString('keyword'));
var gc_id = getQueryString('gc_id');
var a_id = getQueryString('a_id');
var b_id = getQueryString('b_id');
var key = getQueryString('key');
var order = getQueryString('order');
var area_id = getQueryString('area_id');
var price_from = getQueryString('price_from');
var price_to = getQueryString('price_to');
var own_shop = getQueryString('own_shop');
var gift = getQueryString('gift');
var groupbuy = getQueryString('groupbuy');
var xianshi = getQueryString('xianshi');
var virtual = getQueryString('virtual');
var ci = getQueryString('ci');
var myDate = new Date();
var searchTimes = myDate.getTime();

var param = {};
var A = [];
param.page = page;
param.curpage = curpage;
if (gc_id != '') {    
    param.gc_id = gc_id;
}
if (keyword != '') {
    param.keyword = keyword;
}
if (b_id != '') {    
    param.b_id = b_id;
}
if (a_id != '') {    
    param.a_id = a_id;
}
if (key != '') {
    param.key = key;
}
if (order != '') {
    param.order = order;
}

$(function(){
    //属性筛选动画
    $.animationLeft({
        valve : '#search_adv',
        wrapper : '#select-attr-item',
        scroll : '#list-items-scroll'
    });

    $("#header").on('click', '.header-inp', function(){
        location.href = WapSiteUrl + '/tmpl/search.html?keyword=' + keyword;
    });
    if (keyword != '') {
    	$('#keyword').html(keyword.replace(/<[^>]+>/g,""));
    }

    // 商品展示形式
    $('#show_style').click(function(){
        if ($('#product_list').hasClass('grid')) {
            $(this).find('span').removeClass('browse-grid').addClass('browse-list');
            $('#product_list').removeClass('grid').addClass('list');
        } else {
            $(this).find('span').addClass('browse-grid').removeClass('browse-list');
            $('#product_list').addClass('grid').removeClass('list');
        }
    });

    // 排序显示隐藏
    $('#sort_default').click(function(){
        if ($('#sort_inner').hasClass('hide')) {
            $('#sort_inner').removeClass('hide');
        } else {
            $('#sort_inner').addClass('hide');
        }
    });
    $('#nav_ul').find('a').click(function(){
        $(this).addClass('current').parent().siblings().find('a').removeClass('current');
        if (!$('#sort_inner').hasClass('hide') && $(this).parent().index() > 0) {
            $('#sort_inner').addClass('hide');
        }
    });
    $('#sort_inner').find('a').click(function(){
        $('#sort_inner').addClass('hide').find('a').removeClass('cur');
        var text = $(this).addClass('cur').text();
        $('#sort_default').html(text + '<i></i>');
    });

    //显示第三方店铺信息
    $('#product_list').on('click', '.goods-store a',function(){
        var $this = $(this);
        var store_id = $(this).attr('data-id');
        var store_name = $(this).text();
        $.getJSON(ApiUrl + '/index.php?act=store&op=store_credit', {store_id:store_id}, function(result){
            var html = '<dl>'
                + '<dt><a href="store.html?store_id=' + store_id + '">' + store_name + '<span class="arrow-r"></span></a></dt>'
                + '<dd class="' + result.datas.store_credit.store_desccredit.percent_class + '">描述相符：<em>' + result.datas.store_credit.store_desccredit.credit + '</em><i></i></dd>'
                + '<dd class="' + result.datas.store_credit.store_servicecredit.percent_class + '">服务态度：<em>' + result.datas.store_credit.store_servicecredit.credit + '</em><i></i></dd>'
                + '<dd class="' + result.datas.store_credit.store_deliverycredit.percent_class + '">发货速度：<em>' + result.datas.store_credit.store_deliverycredit.credit + '</em><i></i></dd>'
                + '</dl>';
            //渲染页面
            
            $this.next().html(html).show();
        });
    }).on('click', '.sotre-creidt-layout', function(){
        $(this).hide();
    });

    //获取商品列表
    get_list();
    $(window).scroll(function(){
        if(($(window).scrollTop() + $(window).height() > $(document).height()-1)){
            get_list();
        }
    });

    //获取筛选项
    search_adv();
});

function get_list() {
    $('.loading').remove();
    if (!hasmore) {
        return false;
    }
    hasmore = false;
    
    $.ajax({
          url: ApiUrl + '/index.php?act=goods&op=goods_list' + window.location.search.replace('?','&'),
          data: param,
          dataType: 'jsonp',
          success : function(result){
        	if(!result) {
        		result = [];
        		result.datas = [];
        		result.datas.goods_list = [];
        	}
            $('.loading').remove();
            param.curpage++;
            var html = template.render('home_body', result);
            $("#product_list .goods-secrch-list").append(html);
            hasmore = result.hasmore;
          }
    });
}

function select_attr_option(_resData){
    $('#chk_attr_content dl.attr-option').click(function(){
        var _attr_list = _resData.attr_list;
        var obj = $(this).find('dt');
        var curr_id = obj.attr('data-id');
        var _sela_id = obj.attr('sela-id');
        var att_html = template.render('attr_option_value_item',{val_list : _attr_list[curr_id], sela_id : _sela_id});
        $('#list-items-value').html(att_html);
        $('#attr_item_value a[data-id="'+_sela_id+'"]').addClass('selected');
        $('#attr_item_value a.atb').click(function(){
            var a_obj = $(this);
            var a_data_id = a_obj.attr('data-id');
            A[curr_id] = a_data_id;
            if(A.length > 0){
                var _tmp_arr = removeEmptyArrayEle(A);
                param.a_id = _tmp_arr.join("_");
            }
            obj.find('span.chk_content').text(a_obj.text());
            obj.attr('sela-id',a_obj.attr('data-id'));
            $("#select_attr_item_value").addClass('right').removeClass('left');
        });
    });
}

function select_brand_option(_resData){
    $('#chk_attr_content dl.brand-option').click(function(){
        var _bitem_obj = $(this);
        var _brand_obj = _resData.brand_list;
        var brand_html = template.render('brand_option_value_item',{val_list : _brand_obj});
        $('#list-items-value').html(brand_html);
        var _selb_id = _bitem_obj.find('dt').attr('data-id');
        $('#brand_item_value a[data-id="'+ _selb_id +'"]').addClass('selected');

        $('#brand_item_value a.brand').click(function(){
            var obj = $(this);
            param.b_id = obj.attr('data-id');
            _bitem_obj.find('dt').attr('data-id',param.b_id);
            _bitem_obj.find('span.chk_content').text(obj.text());
            $("#select_attr_item_value").addClass('right').removeClass('left');
        });
    });
}

function get_search_adv(){
    $.ajax({
        url : ApiUrl + '/index.php?act=index&op=search_adv' + window.location.search.replace('?','&'),
        data : param,
        async : false,
        dataType : 'jsonp',
        success : function(_res){
            //$('#chk_attr_content').html('');
            var _resData = _res.datas;
            var html = template.render('chk_attr_option',_resData);
            $('#chk_attr_content').html(html);
            var _brand_obj = _resData.brand_list;
            var _b_flag = false;
            for(var m in _brand_obj){
                if(m > 0){
                    var _b_html = '<dl class="brand-option">';
                    _b_html += '<dt class="attr_item" data-name="b_id" data-id="0">';
                    _b_html += '<span class="chk_title">品牌</span>';
                    _b_html += '<span class="chk_content">&nbsp;</span>';
                    _b_html += '<span class="chk_more"></span>';
                    _b_html += '</dt>';
                    _b_html += '</dl>';
                    $('#chk_attr_content').append(_b_html);
                    _b_flag = true;
                    break;
                }
            }
            var chk_blist = _resData.checked_brand;
            if(_b_flag){
                for(var m in chk_blist){
                    $('#chk_attr_content dl.brand-option').find('span.chk_content').text(chk_blist[m].brand_name);
                }
            }
            select_attr_option(_resData);
            select_brand_option(_resData);
            //选择属性值动画
            $.animationLeft({
                valve : '#chk_attr_content .attr_item',
                wrapper : '#select_attr_item_value',
                scroll : '#list-items-value'
            });
        }
    });
}

function search_adv() {
    $.ajax({
        url : ApiUrl + '/index.php?act=index&op=search_adv' + window.location.search.replace('?','&'),
        data : param,
        dataType : 'jsonp',
        async : false,
        success : function(result){
            var data = result.datas;
            $('#list-items-scroll').html(template.render('search_items',data));

            if (area_id) {
                $('#area_id').val(area_id);
            }
            if (price_from) {
                $('#price_from').val(price_from);
            }
            if (price_to) {
                $('#price_to').val(price_to);
            }
            if (own_shop) {
                $('#own_shop').addClass('current');
            }
            if (gift) {
                $('#gift').addClass('current');
            }
            if (groupbuy) {
                $('#groupbuy').addClass('current');
            }
            if (xianshi) {
                $('#xianshi').addClass('current');
            }
            if (virtual) {
                $('#virtual').addClass('current');
            }
            if (ci) {
                var ci_arr = ci.split('_');
                for(var i in ci_arr) {
                    $('a[name="ci"]').each(function(){
                        if ($(this).attr('value') == ci_arr[i]) {
                            $(this).addClass('current');
                        }
                    });
                }
            }
            if(gc_id){
                var selc_list = data.class_list.checked_class;
                $('#chk_class .classify-name').text(selc_list.gc_name);
                var _html = template.render('chk_attr_option',data);
                $('#chk_attr_content').html(_html);
                var _sel_attr = data.checked_attr;
                for(var c in _sel_attr){
                    A[c] = _sel_attr[c].attr_value_id;
                }
                var _brand_obj = data.brand_list;
                var _b_flag = false;
                for(var m in _brand_obj){
                    if(m > 0){
                        var _b_html = '<dl class="brand-option">';
                        _b_html += '<dt class="attr_item" data-name="b_id" data-id="0">';
                        _b_html += '<span class="chk_title">品牌</span>';
                        _b_html += '<span class="chk_content">&nbsp;</span>';
                        _b_html += '<span class="chk_more"></span>';
                        _b_html += '</dt>';
                        _b_html += '</dl>';
                        $('#chk_attr_content').append(_b_html);
                        _b_flag = true;
                        break;
                    }
                }
                var chk_blist = data.checked_brand;
                if(_b_flag){
                    for(var m in chk_blist){
                        $('#chk_attr_content dl.brand-option').find('span.chk_content').text(chk_blist[m].brand_name);
                    }
                }
            }

            select_attr_option(data);
            select_brand_option(data);
            $('#chk_class').click(function(){
                var gc_list = data.class_list;
                var top_chtml = template.render('top_class_list',gc_list);
                $('#class-list-items-value').html(top_chtml);
                var selc_item = gc_list.checked_class;

                if(selc_item){ //处理已选中的分类
                    selc_gcid = param.gc_id;
                    var _selc_obj = $('#t-category-list a[data-id="'+selc_gcid+'"]');
                    _selc_obj.addClass('selected');
                    if(_selc_obj.parent().is('li')){ //处理子分类选中
                        var _top_dl = _selc_obj.parents('dl.category-item');//最外层dl
                        var _top_class_a = _top_dl.find('a.category');//上级分类
                        _top_class_a.addClass('cur-show');
                        _top_class_a.find('i.class_more').css({"background-image":"url(../images/arrow_down_b.png)"});
                        _selc_obj.parents('div.child-category-list').toggle();
                    }
                }                

                $('#t-category-list a.category').click(function(){
                    var li_item = $(this).parent();
                    if(li_item.has('div.child-category-list')){
                        var obj = li_item.find('div.child-category-list');
                        if($(this).hasClass('cur-show')){
                            $(this).removeClass('cur-show');
                            $(this).find('i.class_more').css({"background-image":"url(../images/arrow_right_b.png)"});
                        }else{
                            $(this).addClass('cur-show');
                            $(this).find('i.class_more').css({"background-image":"url(../images/arrow_down_b.png)"});
                        }                        
                        obj.toggle();
                    }else{
                        param.gc_id = $(this).attr('data-id');
                        param.a_id = '';
                        param.b_id = '';
                        A = [];
                        $('#chk_attr_content').html('');
                        get_search_adv();
                        $('#chk_class .classify-name').text($(this).find('.class_title').text());
                        $("#select_class_item_value").addClass('right').removeClass('left');
                    }
                });
                $('.child-category-list a').click(function(){
                    param.gc_id = $(this).attr('data-id');
                    param.a_id = '';
                    param.b_id = '';
                    A = [];
                    $('#chk_attr_content').html('');
                    get_search_adv();
                    $('#chk_class .classify-name').text($(this).text());
                    $("#select_class_item_value").addClass('right').removeClass('left');
                });
            });


            //选择分类值动画
            $.animationLeft({
                valve : '#chk_class .attr_item',
                wrapper : '#select_class_item_value',
                scroll : '#class-list-items-value'
            });

            //选择属性值动画
            $.animationLeft({
                valve : '#chk_attr_content .attr_item',
                wrapper : '#select_attr_item_value',
                scroll : '#list-items-value'
            });

            $('#search_submit').click(function(){
                var queryString = '?keyword=' + keyword, ci = '';
                queryString += '&area_id=' + $('#area_id').val();
                if (param.gc_id != '' && typeof(param.gc_id) != 'undefined') {
                    queryString += '&gc_id=' + param.gc_id;
                }
                if(param.a_id != '' && typeof(param.a_id) != 'undefined'){
                    queryString += '&a_id=' + param.a_id;
                }
                if(param.b_id != '' && typeof(param.b_id) != 'undefined'){
                    queryString += '&b_id=' + param.b_id;
                }
                if ($('#price_from').val() != '') {
                    queryString += '&price_from=' + $('#price_from').val();
                }
                if ($('#price_to').val() != '') {
                    queryString += '&price_to=' + $('#price_to').val();
                }
                if ($('#own_shop')[0].className == 'current') {
                    queryString += '&own_shop=1';
                }
                if ($('#gift')[0].className == 'current') {
                    queryString += '&gift=1';
                }
                if ($('#groupbuy')[0].className == 'current') {
                    queryString += '&groupbuy=1';
                }
                if ($('#xianshi')[0].className == 'current') {
                    queryString += '&xianshi=1';
                }
                if ($('#virtual')[0].className == 'current') {
                    queryString += '&virtual=1';
                }
                $('a[name="ci"]').each(function(){
                    if ($(this)[0].className == 'current') {
                        ci += $(this).attr('value') + '_';
                    }
                });
                if (ci != '') {
                    queryString += '&ci=' + ci;
                }
                window.location.href = WapSiteUrl + '/tmpl/product_list.html' + queryString;
            });
            $('a[nctype="items"]').click(function(){
                var myDate = new Date();
                if(myDate.getTime() - searchTimes > 300) {
                    $(this).toggleClass('current');
                    searchTimes = myDate.getTime();
                }
            });
            $('input[nctype="price"]').on('blur',function(){
                if ($(this).val() != '' && ! /^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test($(this).val())) {
                    $(this).val('');
                }
            });
            $('#reset').click(function(){
                $('a[nctype="items"]').removeClass('current');
                $('input[nctype="price"]').val('');
                $('#area_id').val('');
                param.gc_id = '';
                param.a_id = '';
                param.b_id = '';
                A = [];
                $('#chk_class .classify-name').text('');
                $('#chk_attr_content').html('');
            });

        }
    });
}

function removeEmptyArrayEle(arr){
    var _r_arr = arr.filter(function(x) {
        return typeof(x) != undefined;
        });
    return _r_arr;
}

function init_get_list(o, k) {
    order = o;
    key = k;
    curpage = 1;
    hasmore = true;
    $("#product_list .goods-secrch-list").html('');
    $('#footer').removeClass('posa');
    get_list();
}